import { Directive } from 'vue'

export default function useDirective() {

    type DragBinding = {
        top?: number
        right?: number
        bottom?: number
        left?: number
        [key:string]: any
    }
    //拖拽
    const vDrag: Directive = {
        mounted(el:HTMLElement, binding:any) {
            let dragElement = el.firstElementChild as HTMLElement
            let {left, top, right, bottom} = binding.value as DragBinding
            if (!dragElement) return 
            dragElement.style.cursor = 'move'
            el.style.userSelect = "none"
            el.style.position = 'absolute'
            el.style.top = top ? `${top}px`:''
            el.style.right = right ? `${right}px`:''
            el.style.bottom = bottom ? `${bottom}px`:''
            el.style.left = left ? `${left}px`:''
            
            let [offsetX, offsetY] = [-1, -1];
            let parent:HTMLElement = el.parentElement!
            let isDraging = false
            dragElement.onmousedown = (down:MouseEvent) => {
                if (isDraging) return false
                isDraging = true
                let {width:pWidth, height: pHeight} = parent.getBoundingClientRect()
                let { width, height} = el.getBoundingClientRect()
                let [maxLeft, maxTop] = [pWidth - width, pHeight - height]
                offsetX = down.offsetX;
                offsetY = down.offsetY;

                window.onmousemove = (move:MouseEvent) => {
                    let left = move.clientX - offsetX;
                    let top = move.clientY - offsetY;
                    if (left < 0) left = 0
                    if (top < 0) top = 0
                    if (left >= maxLeft) left = maxLeft
                    if (top >= maxTop) top = maxTop;
                    el.style.left = left + "px";
                    el.style.top = top + "px";
                  }

                // 3.鼠标左键抬起时不允许拖拽-mouseup
                window.onmouseup = () => {
                    isDraging = false
                    window.onmousemove = null
                    window.onmousedown = null
                }
            }
        }
    }

    return { vDrag }
}